import { View, Text, Button, Map } from '@tarojs/components'
import { useState } from 'react'
import Taro, { useLoad } from '@tarojs/taro'
import './index.less'

export default function StoreMap() {
  const [selectedStore, setSelectedStore] = useState(null)
  const [mapCenter, setMapCenter] = useState({
    latitude: 39.908823,
    longitude: 116.397470
  })

  const stores = [
    {
      id: 1,
      name: '万达广场店',
      address: '朝阳区建国路93号万达广场3楼',
      phone: '010-12345678',
      hours: '09:00-21:00',
      latitude: 39.908823,
      longitude: 116.397470,
      services: ['普通洗涤', '干洗', '修补', '皮具护理']
    },
    {
      id: 2,
      name: '银泰城店',
      address: '海淀区中关村大街1号银泰城2楼',
      phone: '010-87654321',
      hours: '10:00-22:00',
      latitude: 39.983424,
      longitude: 116.318417,
      services: ['普通洗涤', '干洗', '修补']
    },
    {
      id: 3,
      name: '大悦城店',
      address: '西城区西单北大街131号大悦城1楼',
      phone: '010-11223344',
      hours: '09:30-21:30',
      latitude: 39.906901,
      longitude: 116.374912,
      services: ['普通洗涤', '干洗', '皮具护理']
    }
  ]

  const markers = stores.map(store => ({
    id: store.id,
    latitude: store.latitude,
    longitude: store.longitude,
    title: store.name,
    iconPath: '/assets/icons/store-marker.png',
    width: 30,
    height: 30
  }))

  useLoad(() => {
    // 获取用户当前位置
    Taro.getLocation({
      type: 'gcj02',
      success: (res) => {
        setMapCenter({
          latitude: res.latitude,
          longitude: res.longitude
        })
      },
      fail: () => {
        console.log('获取位置失败，使用默认位置')
      }
    })
  })

  const handleMarkerTap = (e) => {
    const markerId = e.detail.markerId
    const store = stores.find(s => s.id === markerId)
    setSelectedStore(store)
  }

  const handleNavigation = (store) => {
    Taro.openLocation({
      latitude: store.latitude,
      longitude: store.longitude,
      name: store.name,
      address: store.address
    })
  }

  const handleCall = (phone) => {
    Taro.makePhoneCall({
      phoneNumber: phone
    })
  }

  const handleBooking = (store) => {
    Taro.navigateTo({
      url: `/pages/booking/index?type=store&storeId=${store.id}`
    })
  }

  return (
    <View className='store-map-page'>
      {/* 地图 */}
      <Map
        className='map-container'
        latitude={mapCenter.latitude}
        longitude={mapCenter.longitude}
        markers={markers}
        onMarkerTap={handleMarkerTap}
        showLocation
        showScale
        showCompass
      />

      {/* 门店列表 */}
      <View className='store-list'>
        <Text className='list-title'>附近门店</Text>
        {stores.map(store => (
          <View 
            key={store.id} 
            className={`store-item ${selectedStore?.id === store.id ? 'selected' : ''}`}
            onClick={() => setSelectedStore(store)}
          >
            <View className='store-info'>
              <Text className='store-name'>{store.name}</Text>
              <Text className='store-address'>{store.address}</Text>
              <Text className='store-hours'>营业时间：{store.hours}</Text>
              <View className='store-services'>
                {store.services.map((service, index) => (
                  <Text key={index} className='service-tag'>{service}</Text>
                ))}
              </View>
            </View>
            <View className='store-actions'>
              <Button 
                size='mini'
                onClick={(e) => {
                  e.stopPropagation()
                  handleCall(store.phone)
                }}
                className='action-btn call-btn'
              >
                📞 电话
              </Button>
              <Button 
                size='mini'
                onClick={(e) => {
                  e.stopPropagation()
                  handleNavigation(store)
                }}
                className='action-btn nav-btn'
              >
                🧭 导航
              </Button>
              <Button 
                size='mini'
                type='primary'
                onClick={(e) => {
                  e.stopPropagation()
                  handleBooking(store)
                }}
                className='action-btn book-btn'
              >
                📅 预约
              </Button>
            </View>
          </View>
        ))}
      </View>

      {/* 选中门店详情 */}
      {selectedStore && (
        <View className='store-detail-popup'>
          <View className='popup-header'>
            <Text className='popup-title'>{selectedStore.name}</Text>
            <Button 
              size='mini'
              onClick={() => setSelectedStore(null)}
              className='close-btn'
            >
              ✕
            </Button>
          </View>
          <View className='popup-content'>
            <Text className='detail-address'>📍 {selectedStore.address}</Text>
            <Text className='detail-phone'>📞 {selectedStore.phone}</Text>
            <Text className='detail-hours'>🕐 {selectedStore.hours}</Text>
            <View className='detail-services'>
              <Text className='services-title'>服务项目：</Text>
              <View className='services-list'>
                {selectedStore.services.map((service, index) => (
                  <Text key={index} className='service-item'>{service}</Text>
                ))}
              </View>
            </View>
          </View>
          <View className='popup-actions'>
            <Button 
              onClick={() => handleCall(selectedStore.phone)}
              className='popup-btn call'
            >
              拨打电话
            </Button>
            <Button 
              onClick={() => handleNavigation(selectedStore)}
              className='popup-btn nav'
            >
              前往导航
            </Button>
            <Button 
              type='primary'
              onClick={() => handleBooking(selectedStore)}
              className='popup-btn book'
            >
              立即预约
            </Button>
          </View>
        </View>
      )}
    </View>
  )
}